<template>
  <a-card>
    <a-form-model ref="ruleForm" :model="instructionSheetData" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }" :rules="editModel != 0 ? rules : {}">
      <title-name :title="isAudit ? '分包签证指令单' : '基础信息'"></title-name>
      <custom-form :isEmit="false" :formList="formList" :form="instructionSheetData" :editModel="editModel == 0 ? '' : ''" @select="selectOrg"  @getProjectInfo="getProjectInfo">
        <template v-slot:table>
          <a-form-model-item class="mb20" label=" " :colon="false">
            <a-button v-if="editModel != 0 && currentStep == 0" type="primary" class="mb12" icon="plus" @click="addline()"> 添加行 </a-button>
            <s-table
              bordered
              ref="table"
              tableLayout="fixed"
              size="default"
              rowKey="key"
              :columns="editModel == 0 || currentStep != 0 ? columnsLook : columns"
              :data="loadData"
              :alert="true"
              show-size-changer
              show-quick-jumper
              :showPagination="false"
            >
              <template slot="deductionTypeId" slot-scope="text, record">
                <div class="form-item">
                  <template>
                    <a-select placeholder="请选择" :disabled="editModel == 0 || currentStep != 0" v-model="record.deductionTypeId" @change="changedeductionTypeId(record)">
                      <a-select-option v-for="(i, index) in unitTypeList" :key="index" :value="i.value">{{ i.label }}</a-select-option>
                    </a-select>
                  </template>
                </div>
              </template>
              <template slot="deductionId" slot-scope="text, record">
                <div class="form-item">
                  <template v-if="record.deductionTypeId == '分公司'">
                    <SelectSubCompany :disabled="editModel == 0 || currentStep != 0" :getAll="true" :autoSelected="false" :hiddenSelfBran="true" v-model="record.deductionId" placeholder="请选择" />
                  </template>
                  <template v-else-if="record.deductionTypeId == '分包商'">
                    <SelectSubcontractorCode
                      :disabled="editModel == 0 || currentStep != 0"
                      placeholder="请选择"
                      v-model="record.deductionId"
                      :form="instructionSheetData"
                      :isClear="editModel == 2"
                      keyValue="projectId"
                    ></SelectSubcontractorCode>
                  </template>
                  <template v-else>
                    <BaseInput :disabled="editModel == 0 || currentStep != 0" v-model="record.deductionId" placeholder="请输入" />
                  </template>
                </div>
              </template>
              <template slot="action" slot-scope="text, record, index">
                <a-popconfirm title="确定要删除?" @confirm="() => (instructionSheetData.serDTOS.splice(index, 1), $refs.table.refresh(true))">
                  <a>删除</a>
                </a-popconfirm>
              </template>
            </s-table>
          </a-form-model-item>
        </template>
      </custom-form>
    </a-form-model>
    <!-- 页脚操作栏 -->
    <div class="btn_box page-btn-right-top" v-if="editModel != 0 && currentStep == 0">
      <a-button class="button_right" v-if="instructionSheetData.auditStatus == 'REJECTED'" type="primary" :loading="loadingBtn.REJECTED" @click="handleSubmit('REJECTED')">保存</a-button>
      <a-button v-else class="button_right" type="primary" :loading="loadingBtn.DRAFT" @click="handleSubmit('DRAFT')">保存草稿</a-button>
      <a-button class="button_right" type="primary" :loading="loadingBtn.SUBMITTED" @click="handleSubmit('SUBMITTED')">提交</a-button>
      <a-button @click="handleActiveClose">关闭</a-button>
    </div>
    <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
  </a-card>
</template>

<script>
import { getMatters, addInstruction, updateInstruction } from '@/api/businessAffairs/subcontractVisa'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 项目
import SelectSubcontractorCode from '@/components/Select/SelectSubcontractorCode' // 分包商
import BSelect from '@/components/BComponents/BSelect'
import subcontract from '@/api/legal/branchContract/subcontract'
import { randomString } from '@/utils/util.js'
const columnsLook = [
  {
    title: '序号',
    width: 80,
    dataIndex: 'index',
    customRender() {
      return arguments[2] + 1
    }
  },
  {
    title: '被扣款单位类型',
    dataIndex: 'deductionTypeId',
    width: 300,
    scopedSlots: { customRender: 'deductionTypeId' }
  },

  {
    title: '被扣款单位',
    dataIndex: 'deductionId',
    scopedSlots: { customRender: 'deductionId' }
  }
]
const columns = [
  {
    title: '序号',
    width: 80,
    dataIndex: 'index',
    customRender() {
      return arguments[2] + 1
    }
  },
  {
    title: '被扣款单位类型',
    dataIndex: 'deductionTypeId',
    width: 300,
    scopedSlots: { customRender: 'deductionTypeId' }
  },

  {
    title: '被扣款单位',
    dataIndex: 'deductionId',
    scopedSlots: { customRender: 'deductionId' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: 120,
    scopedSlots: { customRender: 'action' }
  }
]
export default {
  name: 'instructionSheet',
  components: {
    SelectSubCompany,
    SelectProject,
    SelectSubcontractorCode,
    BSelect
  },
  props: {
    instructionSheetData: {
      type: Object,
      default() {
        return { contractNameId: '' }
      }
    },
    isAudit: {
      type: Boolean,
      default: false
    },
    currentStep: {
      type: [Number, String],
      default: -1
    },
    editModel: {
      type: [Number, String],
      default: 2
    }
  },
  data() {
    this.columns = columns
    this.columnsLook = columnsLook
    return {
      loadingBtn: {
        DELETE: false,
        DRAFT: false,
        SUBMITTED: false,
        REJECTED: false
      },
      findCountQueryParam: {
        pageNo: 1,
        pageSize: 10000,
        query: {}
      },
      loadData: () => {
        return new Promise((resolve, reject) => {
          resolve({
            data: this.instructionSheetData.serDTOS || []
          })
        })
      },
      //单位类型
      unitTypeList: [
        {
          label: '分公司',
          value: '分公司'
        },
        {
          label: '分包商',
          value: '分包商'
        },
        {
          label: '非过账甲指分包',
          value: '非过账甲指分包'
        }
      ],
      rules: {
        contractNameId: [{ required: true, message: '请选择' }],
        subcontractorScc: [{ required: true, message: '请选择' }],
        name: [{ required: true, message: '请输入' }],
        constructionSite: [{ required: true, message: '请输入' }],
        code: [{ required: true, message: '请输入' }],
        matters: [{ required: true, message: '请选择' }],
        isOtherDeduction: [{ required: true, message: '请选择' }],
        contents: [{ required: true, message: '请输入' }]
      },
      optionsIssue: [], //工程指令签发事项
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },
 async mounted() {
    getMatters({ type: '2' }).then((res) => {
      this.optionsIssue = res.data
      this.optionsIssue.forEach((item) => {
        item.label = item.name
        item.value = item.id
      })
    })
     //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('comm_project_bidding_sign_instruction')
  },
  watch: {
    instructionSheetData(e) {
      this.$nextTick(() => {
        this.$refs?.table?.refresh(true)
      })
    }
  },
  methods: {
    //选择单位
    selectOrg(val) {
        if (val && val.length) {
            this.form.branchComId = val[val.length - 2].orgId;
            this.form.project = { key: val[val.length - 1].projectId, lable: val[val.length - 1].projectName };
        }
    },
    //获取项目详情
    getProjectInfo(e) {
        this.instructionSheetData.projectDeptId = e.projectDeptOrgId
    },
    /**
     * 获取分包合同下拉框
     */
    async getNameList() {
      if (this.instructionSheetData.projectId && this.instructionSheetData.subContractUnitName) {
        let req = {
          projectId:this.instructionSheetData.projectId,
          subSupplyCompany:this.instructionSheetData.subContractUnitName
        }
        // this.findCountQueryParam.query.subSupplyCompany = this.form.subcontractorName
        return subcontract
          .getSubContractByScc(req).then((res) => {
            if (res.data?.length > 0) {
              res.data.map((item) => {
                item.name = item.contractName
                item.id = item.contractId
              })
            }
            return { code: 200, data: res.data }
          })
          .catch(() => {
            return { code: 200, data: [] }
          })
      }
      return { code: 200, data: [] }
    },
    changedeductionTypeId(record) {
      console.log(record)
      record.deductionId = ''
    },
    // 表格添加行
    addline() {
      if (!this.instructionSheetData.serDTOS) {
        this.instructionSheetData.serDTOS = []
      }
      this.instructionSheetData.serDTOS.push({
        key: randomString(8),
        deductionTypeId: undefined,
        deductionId: undefined
      })
      this.$refs.table?.refresh(true)
    },
    /**
     * 表单验证
     */
    validateForm() {
      let flag1 = true
      let flag2 = true
      this.$refs.ruleForm.validate((e) => {
        flag1 = e
      })
      if (this.instructionSheetData.isOtherDeduction == 1) {
        if (this.instructionSheetData.serDTOS.length == 0) {
          this.$message.warning('请添加表格数据')
          flag2 = false
          return false
        }
        this.instructionSheetData.serDTOS.forEach((i) => {
          if (!i.deductionTypeId || !i.deductionId) {
            flag2 = false
          }
        })
        if (!flag2) {
          this.$message.warning('请填写表格数据')
        }
      }

      if (flag1 && flag2) {
        return true
      } else {
        this.$message.warning("请填写完所有必填项信息")
        return false
      }
    },
    /**
     * 提交表单
     */
    handleSubmit(status) {
      if (status == 'SUBMITTED' && !this.validateForm()) {
        return
      }
      this.okSubmit(status)
    },
    okSubmit(status) {
      this.setProcessConfig = null;
      this.loading = true
      this.loadingBtn[status] = true

      let instructionSheetData = this.$clone(this.instructionSheetData)
      instructionSheetData.auditStatus = status
      instructionSheetData.post = this.$userInfo().currentPost.postCode
      instructionSheetData.isOtherDeduction = this.instructionSheetData.isOtherDeduction == 1

      let api = [updateInstruction, addInstruction][this.editModel - 1] // 根据操作切换url地址
      this.submitApprovalConfirm(status =='SUBMITTED'?this.processConfig:6, (flag)=>{
        if(!flag) {
          this.loading = false
          this.loadingBtn[status] = false
          return
        }
      api(instructionSheetData)
        .then((res) => {
          this.loading = false
          this.loadingBtn[status] = false
          this.$message.success(status == 'SUBMITTED' ? '提交成功！' : '保存成功')
          if (status =='SUBMITTED') {
          //提交时，返回id
             this.businessId = res.data.id;
             this.setProcessConfig = this.processConfig;
               return
            }else{
              this.$multiTab.close()
            }
        })
        .catch(() => {
          this.loadingBtn[status] = false
          this.loading = false
          this.$message.warning(err.data.message)
        })
      })
    },
    /**
     * 动态关闭
     */
    handleActiveClose() {
      this.isBack ? this.$router.go(-1) : this.businessId ? window.close() : this.$multiTab.close()
    }
  },
  computed: {
    formList() {
      return [
       {
          label: '所属单位',
          type: 'orgTree',
          keyName: 'projectId',
          rules: [{ required: true, message: '请选择项目名称', trigger: 'change' }],
          span: 16,
          isAutoSelectFirst: true,
          isNeedAuth:true ,
          checkStrictly: true,
          disabled: true,
          viewName: "viewName",
        },
        // {
        //   type: SelectSubCompany,
        //   keyName: 'branchComId',
        //   label: '所属分公司',
        //   disabled: true,
        //   attrs: {
        //     isDefaultSelected: this.editModel == 2,
        //     autoSelected: this.editModel == 2
        //   }
        // },
        // {
        //   type: SelectProject,
        //   keyName: 'projectId',
        //   label: '所属项目',
        //   disabled: true,
        //   attrs: {
        //     isDefaultSelected: this.editModel == 2,
        //     autoSelected: this.editModel == 2,
        //     keyValue: 'branchComId',
        //     isClear: this.editModel == 2,
        //     isEdit: this.editModel != 2,
        //     form: this.instructionSheetData
        //   },
        //   selectChange: (e) => {
        //     console.log(e)
        //     this.instructionSheetData.projectDeptId = e?.projectDeptId
        //   }
        // },
        {
          keyName: 'subContractUnitName',
          type: 'a-input',
          disabled: true,
          label: '分包商名称',
          placeholder: '自动带出',
          hidden:this.editModel !== 0 ,
        },
        {
          type: SelectSubcontractorCode,
          keyName: 'subcontractorScc',
          label: '分包商名称',
          disabled: this.editModel == 0 || this.currentStep != 0,
          hidden:this.editModel == 0,
          attrs: {
            keyValue: 'projectId',
            isClear: this.editModel == 2,
            isEdit: this.editModel != 2,
            form: this.instructionSheetData
          },
          selectChange: (e, b) => {
            this.$set(this.instructionSheetData, 'subContractUnitName', e?.name)
            this.$set(this.instructionSheetData, 'contractNameId', undefined)
          }
        },
        {
          keyName: 'contractName',
          type: 'a-input',
          disabled: true,
          label: '合同名称',
          placeholder: '自动带出',
          hidden:this.editModel !== 0
        },
        {
          keyName: 'contractNameId',
          type: BSelect,
          disabled: this.editModel == 0 || this.currentStep != 0,
          hidden:this.editModel == 0,
          label: '合同名称',
          placeholder: '请选择合同名称',
          attrs: {
            form: this.instructionSheetData,
            keyValue: 'subContractUnitName',
            request: this.getNameList
          },
          selectChange: (e) => {
            //切换名称获取数据
            this.$set(this.instructionSheetData, 'contractName', e?.name)
          }
        },
        // {
        //   keyName: 'contractNameId',
        //   type: BSelect,
        //   disabled: this.editModel == 0 || this.currentStep != 0,
        //   label: '合同名称',
        //   attrs: {
        //     form: this.instructionSheetData,
        //     keyValue: 'subContractUnitName',
        //     request: this.getNameList
        //   },
        //   selectChange: (e) => {
        //     //合同名称
        //     this.$set(this.instructionSheetData, 'contractName', e?.name)
        //   }
        // },
        {
          keyName: 'name',
          type: 'BaseInput',
          disabled: this.editModel == 0 || this.currentStep != 0,
          label: '分包签证名称'
        },
        {
          keyName: 'constructionSite',
          type: 'BaseInput',
          disabled: this.editModel == 0 || this.currentStep != 0,
          label: '施工部位'
        },
        {
          keyName: 'code',
          type: 'BaseInput',
          disabled: this.editModel == 0 || this.currentStep != 0,
          label: '指令单编码'
        },
        {
          keyName: 'matters',
          type: 'a-radio-group',
          disabled: this.editModel == 0 || this.currentStep != 0,
          label: '工程指令签发事项',
          span: 24,
          data: this.optionsIssue
        },
        {
          keyName: 'isOtherDeduction',
          type: 'a-radio-group',
          disabled: this.editModel == 0 || this.currentStep != 0,
          label: '是否涉及其他单位扣款事宜',
          data: [
            {
              label: '否',
              value: 0
            },
            {
              label: '是',
              value: 1
            }
          ]
        },
        {
          slot: true,
          hidden: this.instructionSheetData.isOtherDeduction != 1,
          customItemSlot: true,
          keyName: 'table',
          span: 24
        },
        {
          keyName: 'contents',
          type: 'BaseTextarea',
          disabled: this.editModel == 0 || this.currentStep != 0,
          label: '要描述指令内容、原因',
          span: 24
        },
        {
          keyName: 'reviewFileInfoVOList',
          type: 'uploadFile',
          label: '项目指令单',
          disabled: this.editModel == 0 || this.currentStep != 0,
          span: 24,
          businessCode: 'BM07'
        }
      ]
    }
  }
}
</script>

<style lang="less" scoped>
/deep/ .form-item  {
  .ant-input:not([disabled]),
  .ant-select:not(.ant-select-disabled) .ant-select-selection,
  .ant-calendar-picker-input,
  .ant-input-number:not([disabled]),
  .ant-cascader-picker {
    border-color: #e4ac0b;
    background-color: #fff9e8;
  }
  .ant-input-disabled,
  .ant-input-number-disabled .ant-input-number-input,
  .ant-time-picker-input[disabled] {
    border-color: #d9d9d9 !important;
    background-color: #f5f5f5 !important;
  }
  .remark {
    .ant-input {
      border-color: inherit;
      background-color: initial;
    }
  }
}
</style>
